#!/usr/bin/env Rscript
# Copyright (c) 2011-2012, Universite de Versailles St-Quentin-en-Yvelines
#
# This file is part of ASK.  ASK is free software: you can redistribute
# it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


suppressPackageStartupMessages(require(gbm, quietly=T))
args <- commandArgs(trailingOnly = T)

if (length(args) != 4) {
    stop("Usage: gbm_predict <configuration.conf> <model> <requested_file> <output_file>")
}

source(file.path(Sys.getenv("ASKHOME"), "common/configuration.R"))
# read the requested points
req = read.table(args[3])

# Set up categorical variables as factors
i = 0
for (f in conf("factors")) {
  i = i+1
  if (f$type == "categorical") {
    req[,i] = as.factor(req[,i])
  }
}
nfactors=i

output = args[4]
# Load gbm model (gbm1, best.iter)
load(args[2])


print(req)

if (nfactors>1) {
    requested = eval(parse(text=paste("cbind(req[,1:nfactors], V",
                     nfactors+1,"=rep(0, nrow(req)))", sep="")))
} else {
    requested = req
}

pred = predict(gbm1, requested, n.trees=best.iter)
out_data = cbind(requested[,1:nfactors], pred)
write.table(out_data, file=output, row.names=F, col.names=F, quote=F)
